package io.gitee.zhangbinhub.acp.cloud

import com.fasterxml.jackson.databind.ObjectMapper
import io.gitee.zhangbinhub.acp.cloud.constant.AcpCloudLogConstant
import io.gitee.zhangbinhub.acp.cloud.log.AcpCloudLogInfo
import io.gitee.zhangbinhub.acp.cloud.log.consumer.DefaultLogProcess
import io.gitee.zhangbinhub.acp.cloud.log.consumer.LogProcess
import io.gitee.zhangbinhub.acp.core.common.CommonTools
import io.gitee.zhangbinhub.acp.core.common.log.LogFactory
import org.springframework.boot.autoconfigure.AutoConfiguration
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.cloud.stream.config.BindingServiceConfiguration
import org.springframework.context.annotation.Bean

/**
 * 日志服务自动配置
 *
 * @since JDK 17
 */
@AutoConfiguration(before = [BindingServiceConfiguration::class, AcpCloudComponentAutoConfiguration::class])
@ConditionalOnExpression("'\${acp.cloud.log-server.enabled}'.equals('true')")
class AcpCloudLogServerAutoConfiguration {
    private val logFactory = LogFactory.getInstance(this.javaClass)

    @Bean
    @ConditionalOnMissingBean(LogProcess::class)
    fun logProcess(): LogProcess = DefaultLogProcess()

    @Bean(AcpCloudLogConstant.CONSUMER)
    @ConditionalOnMissingBean(name = [AcpCloudLogConstant.CONSUMER])
    fun logConsumer(objectMapper: ObjectMapper, logProcess: LogProcess): (String) -> Unit {
        return {
            try {
                val acpCloudLogInfo: AcpCloudLogInfo = objectMapper.readValue(it, AcpCloudLogInfo::class.java)
                var logType = AcpCloudLogConstant.DEFAULT_TYPE
                if (!CommonTools.isNullStr(acpCloudLogInfo.logType)) {
                    logType = acpCloudLogInfo.logType
                }
                acpCloudLogInfo.logType = logType
                logProcess.process(acpCloudLogInfo)
            } catch (e: Exception) {
                logFactory.error(e.message, e)
            }
        }
    }
}
